package com.xyz.study.netty.guide.bio;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;

/**
 * time socket client
 */
public class BioTimeClient {
    public static void main(String[] args) {
        String ip = "127.0.0.1";
        int port = 8080;
        if (null != args && args.length > 0){
            try{
                port = Integer.parseInt(args[0]);
            } catch (NumberFormatException e){
                System.out.println("The time client use default port 8080.");
            }
        }
        for (int i = 0; i < 5; i++){
            String resp = connectServer(ip, port, "QUERY TIME ORDER");
            System.out.println("Now is : " + resp);
            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

    }

    /**
     * 连接SocketServer并获取返回值
     * @param ip
     * @param port
     * @param param
     * @return
     */
    private static String connectServer(String ip, int port, String param){
        String resp = null;
        try(Socket socket = new Socket(ip, port);
            BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            PrintWriter out = new PrintWriter(socket.getOutputStream(), true)){
            out.println(param);
            System.out.println("Send order 2 server succeed.");
            resp = in.readLine();
        }catch (Exception e){
            e.printStackTrace();
        }
        return resp;
    }
}
